package me.zhengjie.inter.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.business.domain.*;
import me.zhengjie.business.repository.*;
import me.zhengjie.business.service.dto.ZhsqDto;
import me.zhengjie.business.service.mapstruct.ZhsqMapper;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.inter.service.MpMsgService;
import me.zhengjie.inter.service.MpZhsqFhService;
import me.zhengjie.inter.service.MpZhsqPgService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.repository.LocalStorageRepository;
import me.zhengjie.utils.DateTimeUtil;
import me.zhengjie.utils.DefaultUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.StoredProcedureQuery;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @description 服务接口
 * @author xiahongbo
 * @date 2022-07-10
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class MpZhsqFhServiceImpl implements MpZhsqFhService {

    private final ZhsqRepository zhsqRepository;
    private final GsRepository gsRepository;
    private final ZhsqHistoryRepository zhsqHistoryRepository;
    private final FpryRepository fpryRepository;
    private final MpMsgService mpMsgService;
    private final UserService userService;
    private final AdlZhsqRepository adlZhsqRepository;

    @PersistenceContext
    private EntityManager em;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateZhzt(String zt, Long id, String bz) {
        log.info("[MpZhsqFhServiceImpl - updateZhzt]--------------- 手机端复核居家照护 - start");
        Zhsq zhsq = zhsqRepository.findById(id).get();

        ZhsqHistory zhsqHistory = new ZhsqHistory();
        zhsqHistory.setId(IdUtil.simpleUUID());
        zhsqHistory.setUserId(SecurityUtils.getCurrentUserId());
        zhsqHistory.setZhsqId(id);
        zhsqHistory.setType("04");
        zhsqHistory.setBz(bz);

        Long userId = zhsq.getBisUserId();
        UserDto user = userService.findById(userId);

        Msg msg = new Msg();
        msg.setType("WxTemplate");
        msg.setTarget(user.getWxOpenId());
        msg.setSendTime(new Timestamp(System.currentTimeMillis()));
        JSONObject content = new JSONObject();
        content.put("first","尊敬的用户，您提交的待遇申请有新的状态变动。");
        content.put("keyword1",zhsq.getBisZhsqSnryXm());
        content.put("keyword2",DateTimeUtil.getDateTime(zhsq.getLrsj(), "YYYY年MM月dd日"));
        if(zt.equals("06")){
            log.info("[MpZhsqFhServiceImpl - updateZhzt]--------------- 手机端复核居家照护 - 复核已通过");
            log.info("[MpZhsqFhServiceImpl - updateZhzt]--------------- 手机端复核居家照护 - 修改照护状态 - 06");
            zhsqRepository.updateZhzt("06", id);
            content.put("keyword3","复核已通过");
            zhsqHistory.setResult("通过");

            log.info("[MpZhsqFhServiceImpl - updateZhzt]--------------- 手机端复核居家照护 - 发布公告");
            Gs gs = new Gs();
            gs.setBisGsId(IdUtil.simpleUUID());
            gs.setBisGsBt(zhsq.getBisZhsqSnryXm());
            gs.setBisGsNr(zhsq.getBisZhsqSnrySfz().substring(0,6)+"********"+zhsq.getBisZhsqSnrySfz().substring(14));
            gs.setBisGsZhid(zhsq.getBisZhsqId());
            gs.setBisGsZt("0");
            gs.setBisGsRq(DateTimeUtil.getDate());
            gs.setBisGsFbr(String.valueOf(SecurityUtils.getCurrentUserId()));
            gsRepository.save(gs);
        }else {
            log.info("[MpZhsqFhServiceImpl - updateZhzt]--------------- 手机端复核居家照护 - 复核未通过");
            log.info("[MpZhsqFhServiceImpl - updateZhzt]--------------- 手机端复核居家照护 - 修改照护状态 - 01");
            content.put("keyword3","复核未通过");
            zhsqHistory.setResult("未通过");
            zhsqRepository.updateZhzt(DefaultUtil.ZHZT_DZX, id);
            zhsqHistory.setBz(bz);

            log.info("[MpZhsqFhServiceImpl - updateZhzt]--------------- 手机端复核居家照护 - 恢复评估人员复核状态");
            fpryRepository.updateResumeFpryZt(id);
            log.info("[MpZhsqFhServiceImpl - updateZhzt]--------------- 手机端复核居家照护 - ADL结果作废");
            adlZhsqRepository.updateBisZfbs(id);
        }

        content.put("remark","请通过公众号查看。");
        msg.setContent(content.toJSONString());
        if(!StringUtils.isEmpty(msg.getTarget())){
            mpMsgService.create(msg);
        }
        zhsqHistoryRepository.save(zhsqHistory);
        log.info("[MpZhsqFhServiceImpl - updateZhzt]--------------- 手机端复核居家照护 end");
    }

    @Override
    public void checkFhjgzh(String zt, Long id, String bz) {
        log.info("[MpZhsqFhServiceImpl - checkFhjgzh]--------------- 手机端复核机构照护 - start");

        ZhsqHistory zhsqHistory = new ZhsqHistory();
        zhsqHistory.setId(IdUtil.simpleUUID());
        zhsqHistory.setUserId(SecurityUtils.getCurrentUserId());
        zhsqHistory.setZhsqId(id);
        // 当前的状态
        zhsqHistory.setType("04");
        if("-5".equals(zt)) {
            log.info("[MpZhsqFhServiceImpl - checkFhjgzh]--------------- 手机端复核机构照护 - 复核未通过");
            log.info("[MpZhsqFhServiceImpl - checkFhjgzh]--------------- 手机端复核机构照护 - 修改照护状态 - 01");
            zhsqRepository.updateZhzt(DefaultUtil.ZHZT_DZX, id);
            zhsqHistory.setResult("未通过");
            zhsqHistory.setBz(bz);

            log.info("[MpZhsqFhServiceImpl - checkFhjgzh]--------------- 手机端复核机构照护 - 恢复评估人员复核状态");
            fpryRepository.updateResumeFpryZt(id);
            log.info("[MpZhsqFhServiceImpl - updateZhzt]--------------- 手机端复核居家照护 - ADL结果作废");
            adlZhsqRepository.updateBisZfbs(id);
        } else {
            log.info("[MpZhsqFhServiceImpl - checkFhjgzh]--------------- 手机端复核机构照护 - 机构照护申请 - 复核 - 开始 zhid:{}", id);
            log.info("[MpZhsqFhServiceImpl - checkFhjgzh]--------------- 手机端复核机构照护 - 机构照护申请 - 执行2901");

            StoredProcedureQuery storedProcedureQuery = this.em.createNamedStoredProcedureQuery("make2901");

            storedProcedureQuery.setParameter("IR_USER_ID", String.valueOf(SecurityUtils.getCurrentUserId()));
            storedProcedureQuery.setParameter("IR_ZHID", String.valueOf(id));

            storedProcedureQuery.execute();
            int code = (int) storedProcedureQuery.getOutputParameterValue("OR_APPCODE");
            String msg = (String) storedProcedureQuery.getOutputParameterValue("OR_MESSAGE");

            log.info("[MpZhsqFhServiceImpl - checkFhjgzh]--------------- 手机端复核机构照护 - 机构照护申请 - 复核 - 结束 :code:{}，msg:{}", code, msg);
            String[] msgArray = msg.split("\\|");
            if (code == 1) {
                log.info("[MpZhsqFhServiceImpl - checkFhjgzh]--------------- 手机端复核机构照护 - 复核已通过");
                log.info("[MpZhsqFhServiceImpl - checkFhjgzh]--------------- 手机端复核机构照护 - 修改照护状态 - 05");
                zhsqRepository.updateZhzt(DefaultUtil.ZHZT_YRD, id);
                zhsqRepository.updateSpbh(msgArray[1], id);
                zhsqHistory.setResult("通过");
            } else {
                throw new BadRequestException(msg+"。执行2900失败，请联系春卷");
            }
        }
        zhsqHistoryRepository.save(zhsqHistory);
        log.info("[MpZhsqFhServiceImpl - checkFhjgzh]--------------- 手机端复核机构照护 end");
    }
}
